package com.aibili.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.aibili.pojo.GiftInfo;
import com.aibili.pojo.UserFavorability;

@Service("userFavorabilityService")
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class UserFavorabilityService extends BaseService {

	/**
	 * 
	 * @Description 通过 user_id 和 relation_id 来查找好感度信息
	 * @param user_id
	 * @param relation_id
	 * @return
	 */
	public UserFavorability getByTwoid(long user_id, long relation_id) {
		String hql = " from UserFavorability where (user_id = :user_id and relation_id = :relation_id) or (user_id = :relation_id and relation_id = :user_id)";
		UserFavorability info = null;
		info = (UserFavorability) dataDao.getFirstObjectViaParam(hql, new String[] { "user_id", "relation_id" },
				user_id, relation_id);
		return info;
	}

	/**
	 * 
	 * @Description 修改好感度信息
	 * @param info
	 */
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void update(UserFavorability info) {
		dataDao.updateObject(info);
	}

	/**
	 * 
	 * @Description 新增好感度信息
	 * @param info
	 */
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void add(UserFavorability info) {
		dataDao.addObject(info);
	}

	/**
	 * 
	 * @Description 增加好感度 送礼物时 favorability=0, 直接添加exp时 gift_id=0
	 * @param user_id
	 * @param relation_id
	 * @param gift_id
	 * @param favorability
	 */
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void addFavorability(long user_id, long relation_id, long gift_id, int favorability) {
		if (gift_id != 0) { // 通过送礼物增加好感度
			GiftInfo gift = dataDao.getObjectById(GiftInfo.class, gift_id);
			if (gift != null) {
				favorability = gift.getPoint();
			}
		}
		String hql = " from UserFavorability where (user_id = :user_id and relation_id = :relation_id) or (user_id = :relation_id and relation_id = :user_id)";
		UserFavorability user = (UserFavorability) dataDao.getFirstObjectViaParam(hql,
				new String[] { "user_id", "relation_id" }, user_id, relation_id);
		if (user != null) {
			user.setFavorability(user.getFavorability() + favorability);
			dataDao.updateObject(user);
		} else {
			UserFavorability favor = new UserFavorability();
			favor.setUser_id(user_id);
			favor.setRelation_id(relation_id);
			favor.setFavorability(favorability);
			dataDao.addObject(favor);
		}

	}

}
